﻿using DevExpress.Xpo;
using DevExpress.Xpo.Metadata;
using DevExpress.Xpo.Metadata.Helpers;

namespace EasyXaf.BulkOperations;

internal sealed class ObjectCloneHelper
{
    private readonly Session _targetSession;

    public ObjectCloneHelper(Session targetSession)
    {
        _targetSession = targetSession;
    }

    public T Clone<T>(T source)
        where T : class
    {
        if (source == null)
        {
            return null;
        }

        var targetClassInfo = _targetSession.GetClassInfo(source.GetType());
        var target = targetClassInfo.CreateNewObject(_targetSession);

        foreach (XPMemberInfo memberInfo in targetClassInfo.PersistentProperties)
        {
            if (memberInfo is not ServiceField && memberInfo.ReferenceType == null)
            {
                memberInfo.SetValue(target, memberInfo.GetValue(source));
            }
        }

        return (T)target;
    }
}
